package com.lysj.website.common.enumeration;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.lysj.website.common.constant.CommonConstant;
import com.lysj.website.common.web.SelectItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Created by zk on 2019-05-17 14:42
 * @description
 */
public class EnumUtils {

    private static Cache<String, Map<Integer, String>> enumInterfaceMapCache = CacheUtil.newLRUCache(100);

    public static <T extends CodeEnum> String findByCode(Integer code, Class<T> tClass) {
        for (T t : tClass.getEnumConstants()) {
            if (t.getCode().equals(code)) {
                return t.getDescription();
            }
        }
        return "unknown";
    }

    public static <T extends EnumInterface> List<SelectItem> createEnumSelectItem(Class<T> tClass) {
        List<SelectItem> selectItems = new ArrayList<>();
        for (T t : tClass.getEnumConstants()) {
            selectItems.add(new SelectItem(t.getCode().toString(), t.getStatus()));
        }
        return selectItems;
    }

    public static <T extends EnumInterface> String findStatusByCode(Integer code, Class<T> tClass) {
        final String s = findStatus(code,tClass);
        if(s == null){
            return CommonConstant.UNKNOWN;
        }
        return s;
    }

    public static <T extends EnumInterface> boolean checkCode(Integer code, Class<T> tClass){
        final String s = findStatus(code,tClass);
        return s != null;
    }

    private static <T extends EnumInterface> String findStatus(Integer code, Class<T> tClass){
        Map<Integer, String> map = enumInterfaceMapCache.get(tClass.getName());
        if (map == null) {
            map = new HashMap<>();
            for (T t : tClass.getEnumConstants()) {
                map.put(t.getCode(), t.getStatus());
            }
            enumInterfaceMapCache.put(tClass.getName(), map);
        }
        return map.get(code);
    }
}
